<template>
  <div class="modal">
    <el-dialog v-model="centerDialogVisible" title="新建用户" width="30%" center>
      <div class="form">
        <el-form :model="formData" label-width="100px">
          <el-form-item prop="name" label="用户名">
            <el-input v-model="formData.name" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="realname" label="真实姓名">
            <el-input v-model="formData.realname" placeholder="请输入真实姓名"></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input show-password v-model="formData.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item prop="cellphone" label="电话号码">
            <el-input v-model="formData.cellphone" placeholder="请输入电话号码"></el-input>
          </el-form-item>
          <el-form-item prop="roleId" label="选择角色">
            <el-select v-model="formData.roleId" placeholder="请选择角色" style="width: 100%">
              <el-option
                v-for="item in entireRoles"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="departmentId" label="选择部门">
            <el-select v-model="formData.departmentId" placeholder="请选择部门" style="width: 100%">
              <el-option
                v-for="item in entireDepartments"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import useMainStore from '../../../../../store/main/main'
import useSystemStore from '../../../../../store/main/system/system'
import newUserDataAction from '../../../../../store/main/system/system'
import { storeToRefs } from 'pinia'
// 1. 定义内部的属性
const centerDialogVisible = ref(false)
const formData = reactive({
  name: '',
  realname: '',
  departmentId: '',
  roleId: '',
  password: '',
  cellphone: ''
})

// 4. 获取roles/departments数据
const mainStore = useMainStore()
const systemStore = useSystemStore()
const { entireDepartments, entireRoles } = storeToRefs(mainStore) // 保持响应式

// 2. 定义设置dialogvisible方法
function setModelVisible(val: boolean) {
  centerDialogVisible.value = true
}

// 4. 点击确认事件
function handleConfirmClick() {
  centerDialogVisible.value = false
  // 创建用户接口
  systemStore.newUserDataAction(formData)
}

// 3. 暴露出这个方法
defineExpose({ setModelVisible })
</script>

<style scoped lang="less">
.form {
  padding: 0 20px;
}
</style>
